<!--商品分类管理-->
<template>
  <div id="productCategory" class="app-container">
    <!--列表-->
    <div class="table-container flex-main">
      <div class="table-container-header">
        <table-toolbar :remove="false" create-text="新增一级分类" @create="handleCreate" @refresh="handleFilter">
          <template slot="rightTool">
            <search v-model="listQuery.keyword" placeholder="请输入分类名称" @search="handleFilter" />
            <el-tooltip class="item" effect="dark" :content="expandAll?'收缩':'展开'" placement="top">
              <el-button circle :icon="expandAll?'el-icon-arrow-up':'el-icon-arrow-down'" @click="expandAll?handleMerge():handleExpand()" />
            </el-tooltip>
          </template>
        </table-toolbar>
      </div>
      <el-table
        v-if="multipleTable"
        ref="multipleTable"
        :data="list"
        header-cell-class-name="table-header"
        fit
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
        row-key="id"
        height="100%"
        :default-expand-all="expandAll"
        highlight-current-row
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick"
        @sort-change="sortChange">
        <el-table-column label="名称" prop="categoryName" min-width="100" show-overflow-tooltip />
        <el-table-column :show-overflow-tooltip="true" label="图标" prop="categoryIcon" width="70" align="center">
          <template slot-scope="scope">
            <img v-if="scope.row.level ===2" :src="common.getFileView(scope.row.categoryIcon)" style="width:32px;height:32px" @error="handleImageError">
          </template>
        </el-table-column>
        <el-table-column label="是否显示" prop="isShow" width="100">
          <template slot-scope="scope">
            <span v-if="scope.row.isShow===1" class="color-primary">显示</span>
            <span v-if="scope.row.isShow===0" class="color-danger">隐藏</span>
          </template>
        </el-table-column>
        <el-table-column label="绑定品牌" prop="brandIds" width="100">
          <template slot-scope="scope">
            <template v-if="scope.row.level ===3">

              <el-button v-if="scope.row.brandIds" type="text" class="color-primary" @click="handleLoadBindBrand(scope.row)">已绑定</el-button>

              <span v-if="!scope.row.brandIds" class="color-danger">未绑定</span>
            </template>
          </template>
        </el-table-column>
        <el-table-column prop="orders" sortable label="排序" width="100" />
        <el-table-column prop="gmtModified" sortable label="修改时间" width="160">
          <template slot-scope="scope">{{ scope.row.gmtModified | formatDate }}</template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="90">
          <template slot-scope="scope">
            <button-option v-if="scope.row.level !=3" icon="iconNextLevel" icon-type="svg" skin="primary" title="新增下级分类" @click="handleCreateNext(scope.row)" />
            <button-option v-if="scope.row.level ===3" icon="el-icon-s-operation" skin="primary" title="绑定品牌" @click="handleBindBrands(scope.row)" />
            <button-option icon="el-icon-edit" skin="primary" title="编辑" @click="handleUpdate(scope.row)" />
            <button-option icon="el-icon-delete" skin="danger" title="删除" @click="handleRemoveSingle(scope.row)" />
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!--新增/编辑侧边栏-->
    <side-box :show="sideBox.recordShow" :title="sideBox.title" @close="sideBox.recordShow = !sideBox.recordShow">
      <template slot="body">
        <el-form
          ref="dataForm"
          :rules="productCategoryRules"
          :model="productCategoryRecord"
          label-position="right"
          label-width="120px">
          <el-form-item v-if="sideBox.status==='create'" label="上级分类:">{{ productCategoryRecord.parentCategoryName }} </el-form-item>
          <el-form-item label="图标:" prop="categoryIcon">
            <single-image-upload v-model="productCategoryRecord.categoryIcon" :catalog="constants.FILE_CATALOG_PRODUCT_CATEGORY" />
          </el-form-item>
          <el-form-item label="名称:" prop="categoryName">
            <el-input v-model="productCategoryRecord.categoryName" maxlength="10" show-word-limit placeholder="请输入" clearable />
          </el-form-item>
          <el-form-item label="是否显示:" prop="isShow">
            <el-radio-group v-model="productCategoryRecord.isShow">
              <el-radio :label="1">显示</el-radio>
              <el-radio :label="0">隐藏</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="排序:" prop="orders">
            <template slot="label">
              排序
              <el-tooltip class="item" effect="dark" content="值越大越靠前" placement="bottom">
                <i class="el-icon-question" />
              </el-tooltip>
            </template>
            <el-input-number v-model="productCategoryRecord.orders" placeholder="请输入排序" show-word-limit style="width:100%" />
          </el-form-item>
          <el-form-item label="描述:" prop="categoryDesc">
            <el-input
              v-model="productCategoryRecord.categoryDesc"
              :rows="6"
              type="textarea"
              maxlength="200"
              show-word-limit
              placeholder="请输入(限200字以内)" />
          </el-form-item>
        </el-form>
      </template>
      <template slot="foot">
        <el-button type="primary" plain @click="sideBox.status==='create'?createData():updateData()">保存 </el-button>
      </template>
    </side-box>
    <model-dialog
      title="品牌关联"
      :visible.sync="brandDialogVisible"
      :show-close="false"
      width="500px"
      @close="brandDialogVisible=!brandDialogVisible">
      <el-select v-model="bindBrandIds" clearable multiple filterable placeholder="请选择要关联的品牌" style="width:100%">
        <el-option
          v-for="item in listBrands"
          :key="item.id"
          :label="item.brandName"
          :value="item.id" />
      </el-select>
      <template slot="footer">
        <el-button type="primary" @click="doBindBrands">确 定</el-button>
      </template>
    </model-dialog>
    <el-dialog title="绑定的品牌" :visible.sync="dialogVisible" width="260px">
      <el-table :data="bindBrands">
        <el-table-column :show-overflow-tooltip="true" label="Logo" prop="brandLogo" width="70" align="center">
          <template slot-scope="scope">
            <img :src="common.getFileView(scope.row.brandLogo)" class="common-round-image-32" @error="handleImageError">
          </template>
        </el-table-column>
        <el-table-column min-width="150" property="brandName" label="品牌" />
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
export default {
  components: {},

  data() {
    return {
      expandAll: false,
      multipleTable: true,
      list: [],
      listQuery: {
        page: 1,
        limit: this.common.PAGE_LIMIT_DEFAULT,
        keyword: undefined,
        sort: this.common.SORT_DEFAULT
      },

      multipleSelectionRecords: [],
      // 固定写法
      sideBox: {
        recordShow: false,
        title: '',
        status: 'create'
      },
      productCategoryRecord: {},
      productCategoryRules: {
        categoryName: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ],
        orders: [
          { required: true, message: '请输入排序', trigger: 'blur' }
        ]
      },
      dialogVisible: false,
      bindBrands: [],
      brandDialogVisible: false,
      listBrands: [],
      bindBrandIds: []
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    handleMerge() {
      this.multipleTable = false
      this.expandAll = false
      this.$nextTick(() => {
        this.multipleTable = true
      })
    },
    handleExpand() {
      this.multipleTable = false
      this.expandAll = true
      this.$nextTick(() => {
        this.multipleTable = true
      })
    },
    // 表格自带方法开始
    /* 全选/反选*/
    handleSelectionChange(val) {
      this.multipleSelectionRecords = val
    },
    /* 表格行数据单击*/
    handleRowClick(row) {
      this.$refs.multipleTable.toggleRowSelection(row)
    },
    /* 表格列排序*/
    sortChange(data) {
      const { prop, order } = data
      if (prop) {
        if (order === 'ascending') {
          this.listQuery.sort = '+' + prop
        } else {
          this.listQuery.sort = '-' + prop
        }
      } else {
        this.listQuery.sort = this.common.SORT_DEFAULT
      }
      this.handleFilter()
    },
    // 表格自带方法结束

    /* 搜索*/
    handleFilter() {
      this.listQuery = {
        ...this.listQuery,
        page: 1
      }
      this.fetchData()
    },
    /* 重置*/
    handleReset() {
      this.listQuery = {
        ...this.listQuery,
        page: 1,
        limit: this.common.PAGE_LIMIT_DEFAULT,
        keyword: undefined,
        sort: this.common.SORT_DEFAULT
      }
      this.$refs.multipleTable.clearFilter()
      this.$refs.multipleTable.clearSort()
      this.fetchData()
    },
    async fetchData() {
      const response = await this.$store.dispatch('productCategoryTreeTable', this.listQuery)
      this.list = response
    },
    /* 新增*/
    handleCreate() {
      this.productCategoryRecord = {
        orders: 99 - this.list.length,
        isShow: 1,
        parentId: 0,
        parentCategoryName: '顶级分类'
      }
      this.sideBox = {
        status: 'create',
        recordShow: true,
        title: '新增商品分类'
      }
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleCreateNext(row) {
      this.productCategoryRecord = {
        orders: 99 - (row.children ? row.children.length : 0),
        isShow: 1,
        parentId: row.id,
        parentCategoryName: row.categoryName
      }
      this.sideBox = {
        status: 'create',
        recordShow: true,
        title: '新增【' + row.categoryName + '】下级商品分类'
      }
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.$store.dispatch('productCategorySave', this.productCategoryRecord).then(response => {
            this.sideBox.recordShow = false
            this.$modal.msgSuccess('创建成功')
            this.handleReset()
          }).catch(() => {
            this.sideBox.recordShow = true
          })
        }
      })
    },
    /* 编辑*/
    handleUpdate(row) {
      this.productCategoryRecord = Object.assign({}, row) // copy obj
      this.sideBox = {
        status: 'update',
        recordShow: true,
        title: '编辑商品分类'
      }
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.productCategoryRecord)
          delete tempData.children
          this.$store.dispatch('productCategoryUpdate', tempData).then(response => {
            this.sideBox.recordShow = false
            this.$modal.msgSuccess('修改成功')
            this.handleFilter()
          }).catch(() => {
            this.sideBox.recordShow = true
          })
        }
      })
    },

    /* 删除*/
    handleRemoveSingle(row) {
      this.multipleSelectionRecords = []
      this.multipleSelectionRecords.push(row)
      this.$refs.multipleTable.clearSelection()
      this.$refs.multipleTable.toggleRowSelection(row, true)
      this.removeRecord()
    },
    removeRecord() {
      if (this.multipleSelectionRecords.length > 0) {
        const ids = []
        this.multipleSelectionRecords.forEach(function(v, i) {
          ids.push(v.id)
        })
        this.$confirm('此操作将永久删除记录, 是否继续?', '删除提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$store.dispatch('productCategoryRemove', ids).then(response => {
            this.handleReset()
            this.$modal.msgSuccess('删除成功')
          }).catch(() => {})
        }).catch(() => { })
      } else {
        this.$modal.msgWarning('请选择要删除的记录')
      }
    },
    handleLoadBindBrand(row) {
      this.dialogVisible = true
      this.$store.dispatch('productCategoryListBindBrand', row.id).then(res => {
        this.bindBrands = res
        this.$forceUpdate()
      })
    },
    handleBindBrands(row) {
      this.productCategoryRecord = Object.assign({}, row)
      this.brandDialogVisible = true
      if (row.brandIds) {
        this.bindBrandIds = row.brandIds.split(',')
      } else {
        this.bindBrandIds = []
      }
      this.$store.dispatch('productBrandList', {}).then(res => {
        this.listBrands = res
      })
    },
    doBindBrands() {
      if (this.bindBrandIds.length === 0) {
        this.$modal.msgWarning('请至少选择一个需要关联的品牌')
        return
      }
      this.$store.dispatch('productCategoryBindBrand', {
        id: this.productCategoryRecord.id,
        brandIds: this.bindBrandIds
      }).then(res => {
        this.brandDialogVisible = false
        this.$modal.msgSuccess('绑定成功')
        this.fetchData()
      })
    }

  }
}
</script>
<style lang="scss" scoped>
</style>
